<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>共 {{ total }} 条记录</template>
        <template #right>
          <el-button
            size="small"
            type="danger"
            @click="$router.push('/import?type=user')"
          >
            excel导入
          </el-button>
          <el-button
            size="small"
            type="warning"
            :loading="downExcelLoading"
            @click="handleDownloadExcel"
          >
            excel导出
          </el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPermission('point-user-add')"
            @click="addEmployee"
          >
            新增员工
          </el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column
            type="index"
            :index="customIndex"
            label="序号"
            sortable=""
            width="100px"
          />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <!-- {{ row.staffPhoto }} -->
              <img
                v-imgerror
                class="staff"
                :src="row.staffPhoto || defaultImg"
                alt=""
                @click="clickShowCodeDialog(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatter"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            sortable=""
            fixed="right"
            width="280"
          >
            <template #default="{row}">
              <!-- {{ row }} -->
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('point-user-edit')"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">
                角色
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('point-user-del')"
                @click="delEmployee(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page"
          :page-sizes="[4, 8, 16, 32]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <add-employee
          :dialog-form-visible.sync="dialogFormVisible"
          @upData="upData"
        />
        <assign-role
          :show-role-dialog.sync="showRoleDialog"
          :user-id="userId"
        />
        <el-dialog
          width="300px"
          title="二维码"
          :visible="showCodeDialog"
          @close="showCodeDialog = false"
        >
          <!-- 二维码 -->
          <el-row type="flex" justify="center">
            <canvas ref="myCanvas"></canvas>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role'
import EmployeeEnum from '@/constant/employees'
import { delEmployeeApi, getEmployeeListApi } from '@/api/employees'
import { formatDate } from '@/filters/index'
import QrCode from 'qrcode'
import mix from '@/mixins'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  mixins: [mix],
  data() {
    return {
      tableData: [], // 渲染的原始数据
      total: 0,
      page: 1,
      pagesize: 4,
      loading: false,
      dialogFormVisible: false, // 控制新增员工
      showRoleDialog: false, // 控制角色分配
      userId: '',
      downExcelLoading: false,
      showCodeDialog: false, // 控制二维码显影
      // defaultImg:
      //   'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg'
      defaultImg: require('@/assets/common/yyx.jpg')
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      this.loading = true
      const {
        data: { data }
      } = await getEmployeeListApi(this.page, this.pagesize)
      // console.log(data)
      // const tableData = data.rows.map(item => {
      //   item.formOfEmployment = +item.formOfEmployment
      //   return item
      // })
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
    },
    // 一页页面数量发生变化时触发
    handleSizeChange(newVal) {
      this.pagesize = newVal
      this.page = 1
      this.getEmployeeList()
    },
    // 页码发生变化时触发
    handleCurrentChange(newVal) {
      this.page = newVal
      this.getEmployeeList()
    },
    // 用来格式化内容
    // row 当前行的信息
    // column 是当前列的信息
    // cellValue 单元格的值
    // index 索引
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 自定义排序index
    customIndex(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除员工
    async delEmployee(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          this.loading = true
          const { data: message } = await delEmployeeApi(id)
          this.$message.success(message)
          if (this.tableData.length === 1 && this.page > 1) {
            this.page--
          }
          this.getEmployeeList()
          this.loading = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增员工点击显示弹窗
    addEmployee() {
      this.dialogFormVisible = true
    },
    // 更新员工信息数据
    upData() {
      this.getEmployeeList()
    },
    // 点击分配角色,传用户Id
    editRole(id) {
      // console.log(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 导出excel
    handleDownloadExcel() {
      this.downExcelLoading = true
      import('@/vendor/Export2Excel').then(async excel => {
        // console.log(excel)
        const headersArr = [
          '姓名',
          '手机号',
          '入职日期',
          '聘用形式',
          '转正日期',
          '工号',
          '部门'
        ]
        const headersRelations = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const {
          data: {
            data: { rows }
          }
        } = await getEmployeeListApi(this.page, this.total)
        // console.log(rows)
        const arr2 = this.getDoubleDimensionalArray(
          headersArr,
          headersRelations,
          rows
        )
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          // 导出的表格的标题, 是一个数组
          header: headersArr,
          data: arr2, // 是一个二维数组
          // 导出的文件名
          filename: '员工信息表',
          // autoWidth 自适应宽度
          autoWidth: true,
          // 导出的文件扩展名后缀
          bookType: 'xlsx',
          multiHeader,
          merges
        })
        this.downExcelLoading = false
      })
    },
    // 点击图片展示二维码
    clickShowCodeDialog(url) {
      if (!url) return // 有图片才显示弹层
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    getDoubleDimensionalArray(headersArr, headersRelations, rows) {
      // 映射, 返回一个新数组,新数组的内容是遍历过程中函数的返回值
      const res = rows.map(item => {
        const arr = []
        headersArr.forEach(str => {
          const EnglishCode = headersRelations[str]
          if (EnglishCode === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(
              val => val.id === +item[EnglishCode]
            )
            const value = obj ? obj.value : '未知'
            arr.push(value)
          } else if (['correctionTime', 'timeOfEntry'].includes(EnglishCode)) {
            arr.push(formatDate(item[EnglishCode]))
          } else {
            // console.log(18)
            arr.push(item[EnglishCode])
          }
        })
        return arr
        // console.log(arr)
      })
      // console.log(res)
      return res
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
